package com.akina.matchsystem.controller;

import com.akina.matchsystem.common.BaseResponse;
import com.akina.matchsystem.common.ErrorCode;
import com.akina.matchsystem.common.ResultUtils;
import com.akina.matchsystem.contant.CacheKeys;
import com.akina.matchsystem.contant.UserConstant;
import com.akina.matchsystem.model.domain.User;
import com.akina.matchsystem.model.request.*;
import com.akina.matchsystem.utils.EmailUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.akina.matchsystem.exception.BusinessException;
import com.akina.matchsystem.service.UserService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import org.springframework.amqp.rabbit.core.RabbitTemplate;


import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 用户接口
 *@CrossOrigin //解决跨域问题，默认是*
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://yupi.icu">编程导航知识星球</a>
 */
@RestController
@RequestMapping("/user")
//@CrossOrigin(origins = {"http://localhost:3000", "http://192.168.56.1:3000","http://8.138.130.203","http://www.akinafriend.com:3000"},allowCredentials = "true")
@Slf4j
public class UserController {
    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 用户注册
     *
     * @param userRegisterRequest
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        // 校验
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String email = userRegisterRequest.getEmail();
        String code = userRegisterRequest.getCode();

        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword,email,code)) {
            throw new BusinessException(ErrorCode.NULL_ERROR,"注册信息不能留空");
        }
        //在这里校验code
        String codeCache = (String)redisTemplate.opsForValue().get(CacheKeys.REGISTER_CODE + email);
        if(!code.equals(codeCache)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"验证码错误");
        }
        long result = userService.userRegister(userAccount, userPassword, checkPassword,email);

        return ResultUtils.success(result);
    }

    @PostMapping("/sendCode")
    public BaseResponse<Boolean> sendCode(@RequestBody CodeRequest codeRequest) {
        // 校验
        if (codeRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String toEmail = codeRequest.getEmail();
        if (StringUtils.isAnyBlank(toEmail)) {
            return null;
        }
        //生成6位随机数字
        String code = EmailUtils.generateCode();
        codeRequest.setCode(code);
        //异步发送邮箱验证码，把验证码存入redis，
        rabbitTemplate.convertAndSend("akina.direct", "mailCode", codeRequest);
        //五分钟验证码 key：pre+email
        redisTemplate.opsForValue().set(CacheKeys.REGISTER_CODE+toEmail,code,300,TimeUnit.SECONDS);
        return ResultUtils.success(Boolean.TRUE);
    }

    /**
     * 用户登录
     *
     * @param userLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(user);
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        int result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 获取当前用户
     *
     * @param request
     * @return
     */
    @GetMapping("/current")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        long userId = currentUser.getId();
        // TODO 校验用户是否合法
        User user = userService.getById(userId);
        User safetyUser = userService.getSafetyUser(user);
        return ResultUtils.success(safetyUser);
    }
    @GetMapping("/getUser")
    public BaseResponse<User> getUser(String fromId) {
        if (StringUtils.isAnyBlank(fromId)||Integer.parseInt(fromId)<=0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long getUserId = Long.parseLong(fromId);
        // TODO 校验用户是否合法
        User user = userService.getById(getUserId);
        User safetyUser = userService.getSafetyUser(user);
        return ResultUtils.success(safetyUser);
    }


    @GetMapping("/search")
    public BaseResponse<List<User>> searchUsers(String username, HttpServletRequest request) {
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH, "缺少管理员权限");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(username)) {
            queryWrapper.like("username", username);
        }
        List<User> userList = userService.list(queryWrapper);
        List<User> list = userList.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
        return ResultUtils.success(list);
    }
    @GetMapping("/search/tags")
    public  BaseResponse<List<User>> searchUsersByTags(@RequestParam List<String> tagNameList){
        if (CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<User> userList = userService.searchUsersByTags(tagNameList);
        return ResultUtils.success(userList);
    }

    @GetMapping("/recommend")
    public BaseResponse<Page<User>> recommendUsers(long pageSize, long pageNum, HttpServletRequest request) {
       User loginUser=userService.getLoginUser(request);
        //查缓存的key值.
        String keyRedis = String.format("akina:user:recommand:%s", loginUser.getId());
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        //先查下缓存有无，缓存的结构是 <String,Object>
        //Page<User> redisUser =(Page<User>)redisTemplate.opsForValue().get(keyRedis);
        Page<User> redisUser = (Page<User>)valueOperations.get(keyRedis);
        if(redisUser!=null){
            //有缓存直接返回
            return  ResultUtils.success(redisUser);
        }
        //无就查缓存，最后再写回数据库
        QueryWrapper<User> userQueryWrapper=new QueryWrapper<>();
        Page<User> userPage = userService.page(new Page<>(pageNum, pageSize), userQueryWrapper);//page分页查询num和size
        //return ResultUtils.success(userPage);
        //写回缓存中


        try {
            valueOperations.set(keyRedis, userPage,30000,TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            log.error("redis set key error");
        }
        return ResultUtils.success(userPage);
    }


    @PostMapping("/update")
    public  BaseResponse<Integer> updateUser(@RequestBody User user,HttpServletRequest request){
        //从请求头中获取cook，然后根据cookie来获取用户权限信息
        //1校验参数是否为空
        if(user == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //2校验权限，自己和管理员可以更改
        User userLogin = userService.getLoginUser(request);
        //3触发更新,
        int res = userService.updateUser(user,userLogin);
        return ResultUtils.success(res);
    }

    @PostMapping("/update/tags")
    public  BaseResponse<Integer> updateUserTags(@RequestBody UpdateTagRequest updateTagRequest, HttpServletRequest request){
        //从请求头中获取cook，然后根据cookie来获取用户权限信息
        //1校验参数是否为空
        if(updateTagRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求参数为空");
        }
        //2校验权限，自己和管理员可以更改
        User userLogin = userService.getLoginUser(request);
        //3触发更新,
        int res = userService.updateUserTags(updateTagRequest,userLogin);
        return ResultUtils.success(res);
    }



    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody long id, HttpServletRequest request) {
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 获取最匹配的用户
     *
     * @param num
     * @param request
     * @return
     */
    @GetMapping("/match")
    public BaseResponse<List<User>> matchUsers(long num, HttpServletRequest request) {
        if (num <= 0 || num > 20) {
            //限制查数据的量。
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        return ResultUtils.success(userService.matchUsers(num, user));
    }
}
